<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2024 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\common\model\store;

use app\common\model\customer\Package;
use app\common\model\customer\Service;
use cores\BaseModel;
use think\model\relation\BelongsTo;
use think\model\relation\BelongsToMany;

/**
 * 用户模型
 * Class User
 * @package app\common\model
 */
class User extends BaseModel
{
    // 定义表名
    protected $name = 'store_user';

    // 定义主键
    protected $pk = 'store_user_id';

    protected $append = [
        'year_month_str',
        'total_assembly'
    ];

    /**
     * 关联商家记录表
     * @return BelongsTo
     */
    public function store(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\Store", 'store_id');
    }

    /**
     * 关联上级用户记录表
     * @return BelongsTo
     */
    public function parentUser(): BelongsTo
    {
        $module = self::getCalledModule();
        return $this->belongsTo("app\\{$module}\\model\\store\\User", 'parent_user_id');
    }

    /**
     * 关联用户角色表表
     * @return BelongsToMany
     */
    public function role(): BelongsToMany
    {
        return $this->belongsToMany('Role', 'StoreUserRole');
    }

    /**
     * 验证用户名是否重复
     * @param string $userName
     * @return bool
     */
    public static function checkExist(string $userName): bool
    {
        return (bool)static::withoutGlobalScope()
            ->where('user_name', '=', $userName)
            ->where('is_delete', '=', 0)
            ->value('store_user_id');
    }

    /**
     * 商家用户详情
     * @param $where
     * @param array $with
     * @return static|array|null
     */
    public static function detail($where, array $with = [])
    {
        return static::get($where, $with);
    }

    public function getYearMonth()
    {
        $year_month = request()->param('year_month');
        if (!$year_month) {
            return '';
        }
        return strtotime(trim($year_month, '&quot;'));
    }

    public function getYearMonthStrAttr($value)
    {
        $year_month = request()->param('year_month');
        if (!$year_month) {
            return '';
        }
        return date("Y-m", strtotime(trim($year_month, '&quot;')));
    }

    public function getTotalAssemblyAttr($value, $data)
    {
        $commission = 0;
        $year_month = $this->getYearMonth();
        if (!$year_month) {
            return $commission;
        }

        $currTime = strtotime(date('Y-m', $this->getYearMonth()) . date('-d H:i:s'));
        $firstDay = date('Y-m-01', $this->getYearMonth());
        $lastDay = strtotime("$firstDay +1 month -1 day");
        $lastDay = strtotime(date("Y-m-d 23:59:59", $lastDay));
        if ($data['position'] == 0) {
            //销售
            $package_ids = (new Package())->where(['store_user_id' => $data['store_user_id'], 'status' => 2, 'is_delete' => 0])->column('package_id');
            if (!$package_ids) {
                return $commission;
            }
            //收款金额*%
            $where = [
                ['a.create_time', 'between', [strtotime($firstDay), $lastDay]],
                ['a.package_id', 'in', $package_ids],
                ['a.sales_commission_type', '=', 0],
            ];
            $commission += (new Service())->alias('a')
                ->where($where)
                ->where('a.is_delete', '=', 0)
                ->where('c.customer_type', '=', 1)
                ->join('customer c', 'a.customer_id=c.customer_id')
                ->sum('a.sales_commission');
            //固定金额
            $where = [
                ['a.create_time', 'between', [strtotime($firstDay), $lastDay]],
                ['a.package_id', 'in', $package_ids],
                ['a.sales_commission_type', '=', 1],
            ];
            $commission += (new Service())->alias('a')
                ->where($where)
                ->where('a.is_delete', '=', 0)
                ->where('c.customer_type', '=', 1)
                ->join('customer c', 'a.customer_id=c.customer_id')
                ->sum('a.sales_commission');
            //每月提成
            $where = [
                ['a.start_time', '<=', $currTime],
                ['a.end_time', '>=', $currTime],
                ['a.package_id', 'in', $package_ids],
                ['a.sales_commission_type', '=', 2],
            ];
            $commission += (new Service())->alias('a')
                ->where($where)
                ->where('a.is_delete', '=', 0)
                ->where('c.customer_type', '=', 1)
                ->join('customer c', 'a.customer_id=c.customer_id')
                ->sum('a.sales_commission');
        } elseif ($data['position'] == 1) {
            //会计
            $package_ids = (new Package())->where(['kj_user_id' => $data['store_user_id'], 'status' => 2, 'is_delete' => 0])->column('package_id');
            if (!$package_ids) {
                return $commission;
            }
            //收款金额*%
            $where = [
                ['a.create_time', 'between', [strtotime($firstDay), $lastDay]],
                ['a.package_id', 'in', $package_ids],
                ['a.account_commission_type', '=', 0],
            ];
            $commission += (new Service())->alias('a')
                ->where($where)
                ->where('a.is_delete', '=', 0)
                ->where('c.customer_type', '=', 1)
                ->join('customer c', 'a.customer_id=c.customer_id')
                ->sum('a.account_commission');
            //固定金额
            $where = [
                ['a.create_time', 'between', [strtotime($firstDay), $lastDay]],
                ['a.package_id', 'in', $package_ids],
                ['a.account_commission_type', '=', 1],
            ];
            $commission += (new Service())->alias('a')
                ->where($where)
                ->where('a.is_delete', '=', 0)
                ->where('c.customer_type', '=', 1)
                ->join('customer c', 'a.customer_id=c.customer_id')
                ->sum('a.account_commission');
            //每月提成
            $where = [
                ['a.start_time', '<=', $currTime],
                ['a.end_time', '>=', $currTime],
                ['a.package_id', 'in', $package_ids],
                ['a.account_commission_type', '=', 2],
            ];
            $commission += (new Service())->alias('a')
                ->where($where)
                ->where('a.is_delete', '=', 0)
                ->where('c.customer_type', '=', 1)
                ->join('customer c', 'a.customer_id=c.customer_id')
                ->sum('a.account_commission');
        } elseif ($data['position'] == 2) {
            //外勤
            $package_ids = (new Package())->where(['wq_user_id' => $data['store_user_id'], 'status' => 2, 'is_delete' => 0])->column('package_id');
            if (!$package_ids) {
                return $commission;
            }
            //收款金额*%
            $where = [
                ['a.create_time', 'between', [strtotime($firstDay), $lastDay]],
                ['a.package_id', 'in', $package_ids],
                ['a.outworker_commission_type', '=', 0],
            ];
            $commission += (new Service())->alias('a')
                ->where($where)
                ->where('a.is_delete', '=', 0)
                ->where('c.customer_type', '=', 1)
                ->join('customer c', 'a.customer_id=c.customer_id')
                ->sum('a.outworker_commission');
            //固定金额
            $where = [
                ['a.create_time', 'between', [strtotime($firstDay), $lastDay]],
                ['a.package_id', 'in', $package_ids],
                ['a.outworker_commission_type', '=', 1],
            ];
            $commission += (new Service())->alias('a')
                ->where($where)
                ->where('a.is_delete', '=', 0)
                ->where('c.customer_type', '=', 1)
                ->join('customer c', 'a.customer_id=c.customer_id')
                ->sum('a.outworker_commission');
            //每月提成
            $where = [
                ['a.start_time', '<=', $currTime],
                ['a.end_time', '>=', $currTime],
                ['a.package_id', 'in', $package_ids],
                ['a.outworker_commission_type', '=', 2],
            ];
            $commission += (new Service())->alias('a')
                ->where($where)
                ->where('a.is_delete', '=', 0)
                ->where('c.customer_type', '=', 1)
                ->join('customer c', 'a.customer_id=c.customer_id')
                ->sum('a.outworker_commission');
        }
        return $commission;
    }

}
